package com.atguigu.gmall.list.listener;

import com.atguigu.gmall.list.service.GoodsService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/13 16:44 星期四
 * description: 商品上下架的消费者
 */
@Component
@Log4j2
public class SkuUpperOrDownListener {

    @Resource
    private GoodsService goodsService;
    /**
     * 监听上架队列中的消息
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "upper_queue")
    public void upper(Channel channel, Message message){
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //获取消息(需上架的商品Id)
        String s = new String(message.getBody());

        try {
            //上架操作
            goodsService.addGoodsFromDbToEs(Long.parseLong(s));
            //确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                if(messageProperties.getRedelivered()){
                    //拒绝过 保存到日志 再次出现异常则拒绝消费消息并丢弃消息
                    log.error("两次上架操作都失败,商品的id为:" + s);
                    channel.basicReject(deliveryTag,false);
                }else{
                    //上加下或消息确认失败,看消息是否被拒绝过,没有拒绝过再来一次
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e1){
                log.error("拒绝消息失败,上架的商品id为: " + s);
            }
        }
    }

    /**
     * 监听下架队列中的消息
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "down_queue")
    public void down(Channel channel, Message message){
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //获取消息(需上架的商品Id)
        String s = new String(message.getBody());

        try {
            //上架操作
            goodsService.remove(Long.parseLong(s));
            //确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                if(messageProperties.getRedelivered()){
                    //拒绝过 保存到日志 再次出现异常则拒绝消费消息并丢弃消息
                    log.error("两次下架操作都失败,商品的id为:" + s);
                    channel.basicReject(deliveryTag,false);
                }else{
                    //上加下或消息确认失败,看消息是否被拒绝过,没有拒绝过再来一次
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e1){
                log.error("拒绝消息失败,下架的商品id为: " + s);
            }
        }
    }
}
